package com.shwread.android.ui.customview;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.dialog.SelectCityDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import logic.bean.GoodsBaseInfo;
import logic.bean.GoodsPropInfo;
import logic.bean.GoodsSkuMapInfo;
import logic.util.MoneyUtil;
import logic.util.PicassoUtil;
import logic.util.ScreenUtil;
import logic.util.Utils;


/**
 * @author xuzhijun
 * @date 2015年4月2日下午12:43:28
 */
public class GoodsPropPopView
        extends
        Dialog
        implements
        OnClickListener
{
	private Context               mContext;
	
	private View                  view;
	private ImageView imgCover;
	private TextView              tvPrice;
	private TextView              tvStock;
	private MyListView            propListView;
	private Button                btnSubtract;
	private Button                btnPlus;
	private Button                btnConfirm;
	private TextView              tvToBuyCount;
	private View                  bottomView;
	//	private int                            totalStock = 0;
	//	private String                moneyRange = "";
	//	private Map<String, String>            tmpSkuMap;
	//	private boolean               isOK     = false;
	//	private Entry<String, GoodsSkuMapInfo> isOKMap;
	//	private List<Integer>         prices;
	
	private GoodsBaseInfo         goodsBaseInfo;
	private List<GoodsPropInfo>   skuGoodsPropInfoList;
	private List<GoodsPropInfo>   notSkuGoodsPropInfoList;
	private GoodsPropListAdapter  goodsBaseAdapter;
	
	private Map<Integer, String>  selector   = new HashMap<Integer, String>();
	private GoodsPropViewListener listener;
	
	private SkuUtil               skuUtil;
	private List<List<String>>    skuTemp;
	private List<GoodsSkuMapInfo> skuValues;
	private int                   sortRange;
	private int                   freeMoney  = 0;                              ;
	private long                  activityId = -1;                             ;
	
	public GoodsPropPopView(Context context, GoodsBaseInfo goodsBaseInfo) {
		super(context, R.style.goods_pop_dialog);
		this.mContext = context;
		this.goodsBaseInfo = goodsBaseInfo;
		skuUtil = new SkuUtil(goodsBaseInfo);
		initView();
		initData();
		initListener();
	}
	
	public GoodsPropPopView(Context context, GoodsBaseInfo goodsBaseInfo, GoodsPropViewListener listener) {
		super(context, R.style.goods_pop_dialog);
		this.mContext = context;
		this.goodsBaseInfo = goodsBaseInfo;
		this.listener = listener;
		skuUtil = new SkuUtil(goodsBaseInfo);
		initView();
		initData();
		initListener();
	}
	
	public GoodsPropPopView(Context context, GoodsBaseInfo goodsBaseInfo, int freeMoney, long activityId) {
		super(context, R.style.goods_pop_dialog);
		this.mContext = context;
		this.goodsBaseInfo = goodsBaseInfo;
		skuUtil = new SkuUtil(goodsBaseInfo);
		this.freeMoney = freeMoney;
		this.activityId = activityId;
		initView();
		initData();
		initListener();
	}
	
	public GoodsPropPopView(Context context, GoodsBaseInfo goodsBaseInfo, GoodsPropViewListener listener, long activityId, int freeMoney) {
		super(context, R.style.goods_pop_dialog);
		this.mContext = context;
		this.goodsBaseInfo = goodsBaseInfo;
		skuUtil = new SkuUtil(goodsBaseInfo);
		this.freeMoney = freeMoney;
		this.activityId = activityId;
		this.listener = listener;
		initView();
		initData();
		initListener();
	}
	
	private void initView() {
		
		view = LayoutInflater.from(mContext).inflate(R.layout.goods_main_popup, null);
		bottomView = LayoutInflater.from(mContext).inflate(R.layout.goods_main_popup_listview_bottom, null);
		imgCover = (ImageView) view.findViewById(R.id.goods_main_popup_image);
		tvPrice = (TextView) view.findViewById(R.id.goods_main_popup_price);
		tvStock = (TextView) view.findViewById(R.id.goods_main_popup_count_tv);
		btnConfirm = (Button) view.findViewById(R.id.goods_main_popup_confirm);
		propListView = (MyListView) view.findViewById(R.id.goods_main_popup_prop_listview);
		btnSubtract = (Button) bottomView.findViewById(R.id.goods_main_popup_subtract_btn);
		btnPlus = (Button) bottomView.findViewById(R.id.goods_main_popup_plus_btn);
		tvToBuyCount = (TextView) bottomView.findViewById(R.id.goods_main_popup_count_edt);
		propListView.addFooterView(bottomView);
		btnSubtract.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_subtract_unselect);
	}
	
	private void initData() {
		skuGoodsPropInfoList = new ArrayList<GoodsPropInfo>();
		notSkuGoodsPropInfoList = new ArrayList<GoodsPropInfo>();
		for (GoodsPropInfo propInfo : goodsBaseInfo.getProp())
		{
			if (propInfo.isSku())
			{
				skuGoodsPropInfoList.add(propInfo);
			}
			else
			{
				notSkuGoodsPropInfoList.add(propInfo);
			}
		}
		
		skuTemp = skuUtil.skuKeysLList;
		this.setCanceledOnTouchOutside(true);
		Window win = this.getWindow();
		win.getDecorView().setPadding(0, 0, 0, 0);
		WindowManager.LayoutParams lp = win.getAttributes();
		lp.width = LayoutParams.MATCH_PARENT;
		lp.height = ScreenUtil.screenHeight / 7 * 5;
		win.setAttributes(lp);
		win.setGravity(Gravity.BOTTOM);
//		imgCover.setImageUrl(goodsBaseInfo.getCoverUrl());
		PicassoUtil.load(mContext, goodsBaseInfo.getCoverUrl(), R.drawable.bg_small_image, imgCover);
		if (goodsBaseInfo.getPrices().size() < 1)
		{
			tvPrice.setText("¥0.0");
		}
		else if (goodsBaseInfo.getPrices().size() == 1)
		{
			tvPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(goodsBaseInfo.getPrices().get(0) - freeMoney, 100)));
		}
		tvStock.setText("库存：" + goodsBaseInfo.getTotalAmount() + "件");
		if (goodsBaseInfo.getTotalAmount() == 0)
		{
			btnConfirm.setEnabled(false);
			btnConfirm.setBackgroundResource(R.drawable.buttonbg_gray);
		}
		calSku();
		
		this.setContentView(view, lp);
		
		//预加载全国城市数据
		new Thread(){
			@Override
			public void run() {
				SelectCityDialog.initData(mContext);
			}
		}.start();
	}
	
	private void initListener() {
		btnConfirm.setOnClickListener(this);
		btnSubtract.setOnClickListener(this);
		btnPlus.setOnClickListener(this);
	}
	
	//goodsBaseInfo的显示弹窗,不要用show()
	public void showWindow() {
		goodsBaseAdapter = new GoodsPropListAdapter();
		propListView.setAdapter(goodsBaseAdapter);
		
		this.show();
	}
	
	public void setSkuListener(GoodsPropViewListener listener) {
		this.listener = listener;
	}
	
	/**
	 * propList适配器
	 */
	private class GoodsPropListAdapter
	        extends
	        BaseAdapter
	{
		private LvHolder           lvHodler;
		private GoodsPropGvAdapter gvAdapter;
		
		@Override
		public int getCount() {
			//			return goodsBaseInfo == null ? 0 : goodsBaseInfo.getProp().size();
			return skuGoodsPropInfoList == null ? 0 : skuGoodsPropInfoList.size();
		}
		
		@Override
		public Object getItem(int position) {
			//			return goodsBaseInfo.getProp().get(position);
			return skuGoodsPropInfoList.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null)
			{
				lvHodler = new LvHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.goods_main_popup_listview_item, null);
				lvHodler.goodsPropName = (TextView) convertView.findViewById(R.id.goods_main_popup_lv_item_prop_name);
				lvHodler.goodsPropGv = (MyGridView) convertView.findViewById(R.id.goods_main_popup_lv_item_prop_gradview);
				convertView.setTag(lvHodler);
			}
			else
			{
				lvHodler = (LvHolder) convertView.getTag();
			}
			
			lvHodler.goodsPropName.setText(skuGoodsPropInfoList.get(position).getGoodsPropName());
			
			gvAdapter = new GoodsPropGvAdapter(position);
			lvHodler.goodsPropGv.setAdapter(gvAdapter);
			
			return convertView;
		}
		
	}
	
	/**
	 * prop属性里的按钮
	 */
	private class GoodsPropGvAdapter
	        extends
	        BaseAdapter
	{
		private List<Map<String, String>> listPropMaps;
		private Button                    propBtn;
		private List<String>              keys;
		private List<String>              values;
		private boolean                   isSingle = false;
		private GoodsPropInfo             goodsPropInfo;
		private int                       parientPosition;
		
		private List<Button>              btnList;
		
		public GoodsPropGvAdapter(int position) {
			parientPosition = position;
			//			this.goodsPropInfo = goodsBaseInfo.getProp().get(position);
			this.goodsPropInfo = skuGoodsPropInfoList.get(position);
			this.listPropMaps = goodsPropInfo.getGoodsPropValueList();
			btnList = new ArrayList<Button>();
			values = new ArrayList<String>();
			keys = new ArrayList<String>();
			for (Map<String, String> map : listPropMaps)
			{
				for (Entry<String, String> entry : map.entrySet())
				{
					keys.add(entry.getKey());
					values.add(entry.getValue());
				}
			}
			if (listPropMaps.size() < 2)
			{
				isSingle = true;
			}
		}
		
		@Override
		public int getCount() {
			return listPropMaps == null ? 0 : listPropMaps.size();
		}
		
		@Override
		public Object getItem(int position) {
			return listPropMaps.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null)
			{
				propBtn = new Button(mContext);
				propBtn.setTextColor(mContext.getResources().getColor(R.color.text_color_67));
				propBtn.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_grid_item_unselect);
				propBtn.setTag(keys.get(position));
				//				if (isSingle)//属性里只有一个值是直接选中
				//				{
				//					setState(propBtn, goodsPropInfo.getGoodsPropName());
				//				}
				btnList.add(propBtn);
				convertView = propBtn;
			}
			else
			{
				propBtn = (Button) convertView;
			}
			propBtn.setText(values.get(position));
			propBtn.setOnClickListener(new View.OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					if (selector.containsValue(keys.get(position)))
					{
						selector.remove(parientPosition);
					}
					else
					{
						selector.put(parientPosition, keys.get(position));
					}
					skuTemp = skuUtil.getSku(selector);
					//					setState(v, goodsPropInfo.getGoodsPropName());
					calSku();
					goodsBaseAdapter.notifyDataSetChanged();
				}
				
			});
			
			skuReload(position);
			
			return convertView;
		}
		
		private void skuReload(final int position) {
			if (selector.get(parientPosition) != null)
			{
				//				propBtn.setBackgroundResource(R.drawable.button_goods_main_popup_grid_btn);
				//				if (selector.get(parientPosition).equals(keys.get(position)))
				//				{
				//					propBtn.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_grid_item_selected);
				//				}
				//				propBtn.setClickable(true);
				
				if (selector.get(parientPosition).equals(keys.get(position)))
				{
					propBtn.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_grid_item_selected);
					propBtn.setTextColor(mContext.getResources().getColor(R.color.common_white));
				}
				else
				{
					if (skuUtil.getState(skuTemp, selector, parientPosition, position))
					{
						propBtn.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_grid_item_unselect);
						propBtn.setTextColor(mContext.getResources().getColor(R.color.text_color_67));
					}
					else
					{
						//						propBtn.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_grid_item_selected);
						propBtn.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_grid_item_notselect);
						propBtn.setTextColor(mContext.getResources().getColor(R.color.common_gray));
						propBtn.setClickable(false);
					}
					
				}
			}
			else if (skuTemp != null && !skuUtil.getState(skuTemp, selector, parientPosition, position))
			{
				propBtn.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_grid_item_notselect);
				propBtn.setTextColor(mContext.getResources().getColor(R.color.common_gray));
				propBtn.setClickable(false);
			}
		}
		
		//		private void setState(View v, String name) {
		//			isOK = false;
		//			isOKMap = null;
		//			boolean vs = v.isSelected();
		//			for (Button btn : btnList)
		//			{
		//				btn.setSelected(false);
		//			}
		//			if (vs)
		//			{
		//				
		//				tmpSkuMap.remove(name);
		//				tvPrice.setText(" ¥" + moneyRange);
		//				tvStock.setText("库存：" + totalStock + "件");
		//			}
		//			else
		//			{
		//				v.setSelected(true);
		//				tmpSkuMap.put(name, (String) v.getTag());
		//				calSku();
		//			}
		//		}
		
	}
	
	/**
	 * 算选择的属性价格区间,和总库存
	 */
	private void calSku() {
		
		if (skuUtil.props2 == null || skuUtil.props2.size() == 0)
		{
			sortRange = goodsBaseInfo.getTotalAmount();
			tvStock.setText("库存：" + goodsBaseInfo.getTotalAmount() + "件");
			return;
		}
		skuValues = skuUtil.getSkuValues();
		sortRange = 0;
		if (skuValues != null && skuValues.size() > 0)
		{
			int maxPrice = skuValues.get(0).getPrice() - freeMoney;
			int minPrice = skuValues.get(0).getPrice() - freeMoney;
			for (GoodsSkuMapInfo goodsSkuMapInfo : skuValues)
			{
				if (goodsSkuMapInfo.getPrice() - freeMoney > maxPrice)
				{
					maxPrice = goodsSkuMapInfo.getPrice() - freeMoney;
				}
				if (goodsSkuMapInfo.getPrice() - freeMoney < minPrice)
				{
					minPrice = goodsSkuMapInfo.getPrice() - freeMoney;
				}
				sortRange += goodsSkuMapInfo.getStock();
			}
			
			if (maxPrice == minPrice)
			{
				tvPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(maxPrice - goodsBaseInfo.getActivityPrice(), 100)));
			}
			else
			{
				tvPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(minPrice - goodsBaseInfo.getActivityPrice(), 100)) + "-" + Utils.getMoneyFormat(MoneyUtil.divide(maxPrice - goodsBaseInfo.getActivityPrice(), 100)));
			}
			tvStock.setText("库存：" + sortRange + "件");
			if (Integer.parseInt(tvToBuyCount.getText().toString()) > sortRange)
			{
				tvToBuyCount.setText(sortRange + "");
			}
		}
		
	}
	
	private String getSkuPropName(GoodsSkuMapInfo info) {
		String keytString = info.getProperties();
		String[] keys = keytString.split(";");
		StringBuilder result = new StringBuilder();
		if (!Utils.isEmpty(keytString))
		{
			for (int i = 0; i < keys.length; i++)
			{
				for (int j = 0; j < skuUtil.keys2.get(i).size(); j++)
				{
					if (keys[i].equals(skuUtil.keys2.get(i).get(j)))
					{
						if (result.length() > 0)
						{
							result.append(",");
						}
						//					result.append(goodsBaseInfo.getProp().get(i).getGoodsPropName() + ":" + skuUtil.props.get(i).get(j));
						result.append(skuGoodsPropInfoList.get(i).getGoodsPropName() + ": " + skuUtil.props2.get(i).get(j));
					}
				}
				
			}
		}
		return result.toString();
	}
	
	private class LvHolder
	{
		public TextView   goodsPropName;
		public MyGridView goodsPropGv;
	}
	
	@Override
	public void onClick(View v) {
		int count = Integer.parseInt(tvToBuyCount.getText().toString());
		switch (v.getId()) {
			case R.id.goods_main_popup_confirm:
				//				if (selector.size() < goodsBaseInfo.getProp().size())
				if (selector.size() < skuGoodsPropInfoList.size())
				{
					Utils.ToastShow(mContext, "请选择属性");
				}
				else if (listener != null)
				{
					if (skuValues == null || skuValues.size() == 0)
					{
						listener.OK(null, "", Integer.parseInt(tvToBuyCount.getText().toString()), this, activityId, freeMoney);
					}
					else
					{
						listener.OK(skuValues.get(0), getSkuPropName(skuValues.get(0)), Integer.parseInt(tvToBuyCount.getText().toString()), this, activityId, freeMoney);
					}
				}
				break;
			case R.id.goods_main_popup_subtract_btn:
				if (count > 1)
				{
					if (count == 2)
					{
						btnSubtract.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_subtract_unselect);
					}
					else
					{
						btnSubtract.setBackgroundResource(R.drawable.button_goods_main_popup_subtract);
					}
					btnPlus.setBackgroundResource(R.drawable.button_goods_main_popup_plus);
					
					tvToBuyCount.setText(count - 1 + "");
				}
				break;
			case R.id.goods_main_popup_plus_btn:
				if (count < sortRange)
				{
					if (count == (sortRange - 1))
					{
						btnPlus.setBackgroundResource(R.drawable.buttonbg_goods_main_popup_plus_unselected);
					}
					else
					{
						btnPlus.setBackgroundResource(R.drawable.button_goods_main_popup_plus);
					}
					btnSubtract.setBackgroundResource(R.drawable.button_goods_main_popup_subtract);
					
					tvToBuyCount.setText(count + 1 + "");
				}
				break;
		}
	}
}
